import React from 'react';
import styles from './Radio.less';

interface IRadio {
  name?: string;
  label: string | React.ReactNode;
  value: string;
  selected?: boolean;
  children?: React.ReactNode;
  onChange?: (e: React.ChangeEvent) => void;
}

export const Radio: React.FC<IRadio> = props => {
  const { name, label, value, selected, onChange } = props;
  return (
    <div className={styles.radio_wrap}>
      <input
        type="radio"
        name={name}
        value={value}
        id={value}
        className={styles.radio_input}
        onChange={onChange}
        defaultChecked={selected}
      />
      <label htmlFor={value} className={styles.label}></label>
      <label htmlFor={value} className={styles.label_value}>
        {props.children}
      </label>
    </div>
  );
};

interface IRadioGroup {
  name: string;
  children?: React.ReactNode;
  defaultSelected?: string;
  onChange?: (e: React.ChangeEvent) => void;
}

export const RadioGroup: React.FC<IRadioGroup> = props => {
  const { name, children, defaultSelected, onChange } = props;
  return (
    <div>
      {React.Children.map(props.children, child => {
        const { label, value, children } = (child as any).props;
        return (
          <Radio
            name={name}
            value={value}
            label={label}
            children={children}
            onChange={onChange}
            selected={value === defaultSelected}
          />
        );
      })}
    </div>
  );
};
